package com.atguigu.eduservice.service.impl;

import com.atguigu.baseservice.handler.exception.GuliException;
import com.atguigu.baseservice.result.ResultCodeEnum;
import com.atguigu.eduservice.entity.EduVideo;
import com.atguigu.eduservice.entity.EduVideoInfoForm;
import com.atguigu.eduservice.mapper.EduVideoMapper;
import com.atguigu.eduservice.service.EduVideoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 课程视频 服务实现类
 * </p>
 *
 * @author dayouzi
 * @since 2022-10-18
 */
@Service
public class EduVideoServiceImpl extends ServiceImpl<EduVideoMapper, EduVideo> implements EduVideoService {

    @Override
    public boolean getCountByChapterId(String id) {

        //根据章节id查询是否有视频
        QueryWrapper<EduVideo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("chapter_id", id);
        Integer count = baseMapper.selectCount(queryWrapper);
        return null != count && count > 0;
    }

    @Override
    public void saveVideoInfo(EduVideoInfoForm eduVideoInfoForm) {
        EduVideo eduVideo = new EduVideo();
        BeanUtils.copyProperties(eduVideoInfoForm, eduVideo);
        boolean result = this.save(eduVideo);
        if (!result) {
            throw new GuliException(ResultCodeEnum.ADD_ERROR);
        }
    }

    @Override
    public EduVideoInfoForm getVideoInfoFormById(String id) {
        EduVideo eduVideo = this.getById(id);
        if (eduVideo == null) {
            throw new GuliException(ResultCodeEnum.NOT_FOUND);
        }

        EduVideoInfoForm eduVideoInfoForm = new EduVideoInfoForm();
        BeanUtils.copyProperties(eduVideo, eduVideoInfoForm);

        return eduVideoInfoForm;

    }

    @Override
    public void updateVideoInfoById(EduVideoInfoForm eduVideoInfoForm) {
        EduVideo eduVideo = new EduVideo();
        BeanUtils.copyProperties(eduVideoInfoForm, eduVideo);
        boolean result = this.updateById(eduVideo);
        if (!result) {
            throw new GuliException(ResultCodeEnum.SAVE_ERROR);
        }
    }


    @Override
    public boolean removeVideoInfoById(String id) {
        Integer result = baseMapper.deleteById(id);
        return result > 0;

    }

    @Override
    public boolean removeByCourseId(String courseId) {
        QueryWrapper<EduVideo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id", courseId);
        Integer result = baseMapper.delete(queryWrapper);
        return result > 0;
    }
}
